/*
 * Copyright (C) 2010 Graham Allan
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package edu.strath.cis.grallan.findbugs.adaptiveranking.lr;

import edu.strath.cis.grallan.findbugs.adaptiveranking.RankCalculatorStrategy;
import edu.strath.cis.grallan.findbugs.adaptiveranking.arm.ARMRankCalculator;
import edu.strath.cis.grallan.findbugs.adaptiveranking.population.AlertPopulationMap;
import edu.strath.cis.grallan.findbugs.adaptiveranking.population.Population;
import edu.strath.cis.grallan.findbugs.adaptiveranking.population.PopulationExtractor;
import edu.strath.cis.grallan.findbugs.adaptiveranking.population.PopulationType;
import edu.umd.cs.findbugs.BugInstance;

public class LearningRankCalculator implements RankCalculatorStrategy {

	private RankCalculatorStrategy armRankCalculator = new ARMRankCalculator();

	public double calculateRank(PopulationExtractor extractor, BugInstance bug) {
		double learningValue = 0.0d;
		for (AlertPopulationMap alertPopulationMap : extractor.alertPopulationMaps()) {
			Population population = alertPopulationMap.getPopulationFor(bug);
			PopulationType populationType = alertPopulationMap.type();
			double valueToPopulation = population.numberOf(LearningValueRanker.UNCLASSIFIED_MATCHER)
					* populationType.weight();
			learningValue += valueToPopulation;

		}
		int numberOfBugs = extractor.bugCollection().getCollection().size();
		learningValue /= numberOfBugs;

		double armRank = armRankCalculator.calculateRank(extractor, bug);
		double armRankMagnitude = Math.abs(armRank);

		learningValue *= (1 - armRankMagnitude);

		return learningValue;
	}

}